﻿using JX.Infrastructure.LoadBalancer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JX.Infrastructure.Consul
{
    /// <summary>
    /// consul服务构造器
    /// </summary>
    public class ConsulServiceBuilder : IConsulServiceBuilder
    {
        /// <summary>
        /// 服务提供者
        /// </summary>
        public IConsulServiceProvider ConsulServiceProvider { get; set; }
        /// <summary>
        /// 服务名称
        /// </summary>
        public string ServiceName { get; set; }
        /// <summary>
        /// Uri方案  http / https
        /// </summary>
        public string UriScheme { get; set; }
        /// <summary>
        /// 负载均衡策略
        /// </summary>
        public ILoadBalancer LoadBalancer { get; set; }

        /// <summary>
        /// 构造器注入
        /// </summary>
        /// <param name="serviceProvider"></param>
        public ConsulServiceBuilder(IConsulServiceProvider serviceProvider)
        {
            ConsulServiceProvider = serviceProvider;
        }

        /// <summary>
        /// 构建服务地址方法，异步的，path是接口地址
        /// </summary>
        /// <param name="path">服务中的接口地址。例：/health</param>
        /// <returns></returns>
        public async Task<Uri> BuildAsync(string path)
        {
            var serviceList = await ConsulServiceProvider.GetServicesAsync(ServiceName);
            var service = LoadBalancer.Resolve(serviceList);
            var baseUri = new Uri($"{UriScheme}://{service}");
            // 包含了接口的完整服务地址
            var uri = new Uri(baseUri, path);
            return uri;
        }
    }
}
